
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using CStock;
using CUtil;




namespace CStock
{
	/// <summary>
	/// Summary description for DataItem
	/// </summary>
    public partial class DataItem : StockObjectBase, IDataItem
	{
		#region private members

        private string symbol;
        string countryCode;
        private string exchange;
        private string marketType;
        private string expiry;
        bool show100PercentGraph;
        
        private double buyQuote;

        private double priceFirst;
        private string profileName;
        private IProfile  profile;

        Web.WebStockType webStockType;
       

        private int number;
        private DateTime buyDate;

        private double performance;

        private ArrayList selectedIndicators;

        private double currentTotalValue;
        private bool showIndicatorsOnIntradayChart;
        private bool hideIndicatorsOnChart;

        private bool chartCandleStick;
        private double moneyWonLost;
        private int chartNumberToShow;
        private int chartSizeWidth;
        private int chartSizeHeight;

        private double lastPrice;
        private DateTime lastPrice_Date;
        private bool sold;


        protected NameObjectCollection tradeOrders;
			
		private IQuoteWeb quoteWeb;
        protected IOrders orders;
      


		[System.Xml.Serialization.XmlIgnoreAttribute()]
		protected IDataClass dataClass;

        private IFinancialData financialData;
        
        ITradeStep tradeStep;

		private string externalID;

        protected IList<string> indicatorsOnChart;
        private string symbol_intraday;
        private string lastChangePercent;

        private List<IFundamentalData> fundamentalData;
        private List<IFundamentalData> fundamentalData_Quartals;

		#endregion

		#region Constructor
		
        public DataItem()
		{
            PasswordGenerator pw = new PasswordGenerator(false);
            this.iD = pw.Generate();
            financialData = new FinancialData(this);
            ResetPathFromConfiguration();

			//InitDataClassParameters();
			indicatorsOnChart = new List<string>();
            chartCandleStick = false;
            this.webStockType = CStock.Web.WebStockType.Yahoo;
            fundamentalData_Quartals = new List<IFundamentalData>();
            //CreateDataClass();

	
						
		}
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnore()]
        public new IPortfolio Parent
        {
            get
            {

                return this.parent as IPortfolio;

            }
            set
            {
                this.parent = value as IPortfolio;
            }
        }
        public override bool ResetPathFromConfiguration()
        {

            ProgramContext pc = ProgramContext.Instance;
            Debug.Assert(pc != null, "Initialize ProgramContext first ...");
            if (pc != null)
                this.path = pc.Configuration.Directories.DataItemsPath;
            return true;


        }
        public bool Serialize_WithoutDataClass()
        {
            this.ResetPathFromConfiguration();
            IPortfolio portf = this.parent as Portfolio;
            portf.Serialize();
            return base.Serialize();
        }

        public override bool Serialize()
        {

            //beware - IDataItem is saved in portfolio!!
            this.ResetPathFromConfiguration();
            Debug.Assert(dataClass != null, "DataClass is null for: " + this.iD);
            if (this.dataClass != null)
            {
                this.dataClass.Serialize();
            }
            return base.Serialize();
        }

		[Browsable(false)]
		[System.Xml.Serialization.XmlIgnore()]
		public override string Path
		{
			get
			{

                if (!String.IsNullOrEmpty(this.path))
                    this.path = ProgramContext.Instance.Path + "\\DataItems";
				return this.path;
			}
			
		}
		

		#endregion

		#region IDataItem


   


		[Category("Chart")]
        [Browsable(false)]
		public bool ShowIntradayIndicators
		{
			get 
			{ 
                
				return showIndicatorsOnIntradayChart;

			}
			set
			{
				bool oldval = this.showIndicatorsOnIntradayChart;
				this.showIndicatorsOnIntradayChart = value;
				
				if(oldval != this.showIndicatorsOnIntradayChart)
				{
					if(this.parent != null)
					{
                        IPortfolio portf = this.parent as IPortfolio;
                        portf.RaiseObjectChangedEvent(this, "ShowIntradayIndicators", oldval, value);
					}
				}	
				
				
				
			}
		}
        [Category("Exchange Data"), Description(@"Data related to the exchange")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public string ShareName
        {
            get
            {
                return this.iD;
            }
            set
            {
                if (this.parent != null)
                {
                    ((IPortfolio)this.parent).DataItems.Remove(this);

                    string oldval = this.iD;
                    this.iD = value;

                    ((IPortfolio)this.parent).DataItems.Items.Add(this);
                    ((IPortfolio)this.parent).Serialize();
                    //delete old dataClass ...
                    UpdateDataClass();
                    this.Serialize();
                    this.RaiseObjectChangedEvent(this, "Name", oldval, value);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Error - no portfolio set for: " + this.iD);
                }
            }

        }
        [Category("Chart")]
        [Browsable(false)]
        public int ChartNumberToShow
        {
            get
            {
                return this.chartNumberToShow;

            }
            set
            {
                int oldval = this.chartNumberToShow;
                this.chartNumberToShow = value;
                
                if (oldval != this.chartNumberToShow)
                {
                    IPortfolio portf = this.parent as IPortfolio;
                    if (portf != null)
                    {
                        portf.RaiseObjectChangedEvent(this, "ToSerialize", oldval, value);
                    }
                }	
            }
        }
        [Category("Chart")]
        [Browsable(false)]
        public int ChartSizeWidth
        {
            get
            {
                return chartSizeWidth;;

            }
            set
            {
                int oldval = this.chartSizeWidth;
                this.chartSizeWidth = value;

                if (oldval != this.chartSizeWidth)
                {
                    IPortfolio portf = this.parent as IPortfolio;
                    if (portf != null)
                    {
                        portf.RaiseObjectChangedEvent(this, "ToSerialize", oldval, value);
                    }
                }
            }
        }
        [Category("Chart")]
        [Browsable(false)]
        public int ChartSizeHeight
        {
            get
            {
                return chartSizeHeight; ;

            }
            set
            {
                int oldval = this.chartSizeHeight;
                this.chartSizeHeight = value;

                if (oldval != this.chartSizeHeight)
                {
                    IPortfolio portf = this.parent as IPortfolio;
                    if (portf != null)
                    {
                        portf.RaiseObjectChangedEvent(this, "ToSerialize", oldval, value);
                    }
                }
            }
        }
        

        [Category("Chart")]
        [Browsable(false)]
        public bool Show100PercentGraph
		{
			get 
			{
                return this.show100PercentGraph;


			}
			set
			{
                bool oldval = this.show100PercentGraph;
                this.show100PercentGraph = value;

                if (oldval != this.show100PercentGraph)
				{
                    IPortfolio portf = this.parent as IPortfolio;
                    if (portf != null)
					{
                        portf.RaiseObjectChangedEvent(this, "ToSerialize", oldval, value);
					}
				}	
				
			}
		}
		[Category("Chart")]
        [Browsable(false)]
        public bool HideIndicatorsOnChart
		{
			get 
			{ 
				return this.hideIndicatorsOnChart;


			}
			set
			{
				bool oldval = this.hideIndicatorsOnChart;
				this.hideIndicatorsOnChart = value;
				
				if(oldval != this.hideIndicatorsOnChart)
				{
                    IPortfolio portf = this.parent as Portfolio;
                    if (portf != null)
					{
                        portf.RaiseObjectChangedEvent(this, "ToSerialize", oldval, value);
					}
				}	
				
			}
		}


		#endregion
    
		#region properties

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade"), Description(@"Data related to the exchange"),
        DisplayName("Date - Sell")]
        public string DateSell
        {
            get
            {

                
                if (this.sold)
                    return this.lastPrice_Date.ToShortDateString();

                return CalculateLastPriceDate();
               
            }
            set
            {
                try
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        if (this.sold)
                        {
                            this.lastPrice_Date = Convert.ToDateTime(value);
                            IPortfolio portf = this.parent as IPortfolio;
                            portf.RaiseObjectChangedEvent(this, "SerializePortfolio", sold, value);
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Value not correct for date: " + value.ToString());
                }
            }
        }
       
        /// <summary>
        /// to only be serizalized
        /// </summary>
        [Browsable(false)]
        public string LastPrice_Date
        {
            get
            {

                //if (this.financialData != null)
                //    return this.financialData.LastTradeDate;

                return this.lastPrice_Date.ToShortDateString();
            }
            set
            {
                try
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                       this.lastPrice_Date = Convert.ToDateTime(value, CUtil.Conversions.CultureAmerican);
                    }
                }
                catch
                {
                    //System.Windows.Forms.MessageBox.Show("Value not correct for date: " + value.ToString());
                }
            }
        }
 
        [Browsable(false)]
        public double LastPrice
        {
            get
            {
                return this.lastPrice;
            }
            set
            {
                this.lastPrice = value;
                
            }
        }

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade"), Description(@"Data related to the exchange"),
        DisplayName("Price Last")]
        public double PriceLast
        {
            get
            {
                if (this.sold)
                {
                    return this.lastPrice;
                }

                //if(this.financialData != null)
                //    return Convert.ToString(this.financialData.LastQuote.CLOSEc, CUtil.Conversions.CultureAmerican); ;
                return CalculateLastPrice();
                
            }
            set
            {
                try
                {
                    this.lastPrice = value;
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Value not correct for date: " + value.ToString());
                }
            }
        }

        [Browsable(false)]
        public bool SoldSerialize
        {
            get
            {
                return this.sold;
            }
            set
            {
                sold = value;
            }
        }

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade"), Description(@"Data related to the exchange"), DisplayName("Sold")]
        public bool Sold
        {
            get
            {
                return this.sold;
            }
            set
            {
                IPortfolio portf = this.parent as IPortfolio;
                if (value == true)
                {
                    CalculateInitialSellData();
                }
                
                portf.RaiseObjectChangedEvent(this, "SerializePortfolio", sold, value);
                sold = value;
            }
        }
  
     
        [Category("Exchange Data"), Description(@"Data related to the exchange"),
        DisplayName("Change - in %")]
        public string ChangePercent
        {
            get
            {
                DeserializeDataClass();
                if (this.dataClass != null)
                {
                    if (this.dataClass.QuoteCollection != null && this.dataClass.QuoteCollection.Count > 0)
                    {
                        IQuote qu = this.dataClass.QuoteCollection[this.dataClass.QuoteCollection.Count - 1] as IQuote;
                        if (qu != null)
                        {
                            double chPercent = 0f;
                            if (qu.CLOSEc > 0f)
                            {
                                chPercent = qu.Change / qu.CLOSEc * 100;
                            }
                            chPercent = FormatNumbers.FormatFloatWithTwoDigits(chPercent);
                            lastChangePercent = chPercent.ToString();
                            return lastChangePercent;
                        }

                    }
                }
                return string.Empty;
            }
        }
        [Category("Exchange Data"), Description(@"Data related to the exchange"),
        DisplayName("Price - First Available")]
        public string Price_FirstAvailable
        {
            get
            {
                if (this.dataClass != null)
                {
                    if (this.dataClass.QuoteCollection != null && this.dataClass.QuoteCollection.Count > 0)
                    {
                        IQuote qu = this.dataClass.QuoteCollection[0] as IQuote;
                        if (qu != null)
                            return qu.DATE.ToShortDateString();

                    }
                }
                return string.Empty;
            }
            
        }



        [Category("2. Trade")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public IQuoteWeb QuoteWeb
        {
            get
            {
                return this.quoteWeb;
            }
            set
            {
                quoteWeb = value;
            }

        }

      
			
        //}

        //create a browsable property ...
        [Category("Web"), Description(@"Data related to the exchange")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public string Symbol
        {
            get
            {

                return this.symbol;
            }
            set
            {
                this.symbol = value;
                this.financialData.Symbol = value;
                Debug.Assert(this.parent != null, "Parent not set for dataItem + " + this.iD);
                if(this.parent != null)
                    ((IPortfolio)this.parent).Serialize();

            }
        }
        //  [Category("Web"), Description(@"Data related to the exchange")]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        //public string CountryCode
        //{
        //    get
        //    {

        //        return this.countryCode;
        //    }
        //    set
        //    {
        //        this.countryCode = value;
        //        Debug.Assert(this.parent != null, "Parent not set for dataItem + " + this.iD);
        //        if(this.parent != null)
        //            ((IPortfolio)this.parent).Serialize();

        //    }
        //}
        
		
        [Browsable(false)]
        public string SymbolSave
		{
			get
			{
				
				return this.symbol;
			}
			set
			{
                this.symbol = value;
                //if(dataClass != null)
                    this.financialData.Symbol = value;
                
               
				
			}
		}
		[Category("Exchange Data"),Description(@"Data related to the exchange")]
        [Browsable(false)]
		public string Exchange
		{
			get
			{
				
				return this.exchange;
			}
			set
			{
				
				this.exchange = value;
                IPortfolio portf = this.parent as IPortfolio;
                if (portf != null)
				{
                    portf.RaiseObjectChangedEvent(this, "Exchange", null, value);
				}
				
			}
		}
		[Category("Exchange Data"),Description(@"Data related to the exchange")]
        [Browsable(false)]
		public string MarketType
		{
			get
			{
				
				return this.marketType;
			}
			set
			{
				
				this.marketType = value;
                IPortfolio portf = this.parent as IPortfolio;
                if (portf != null)
				{
                    portf.RaiseObjectChangedEvent(this, "MarketType", null, value);
				}
				
			}
		}
        
      
		[Category("Exchange Data"),Description(@"Data related to the exchange")]
        [Browsable(false)]
		public string Expiry
		{
			get
			{
				
				return this.expiry;
			}
			set
			{
				
				this.expiry = value;
                IPortfolio portf = this.parent as IPortfolio;
                if (portf != null)
				{
                    portf.RaiseObjectChangedEvent(this, "Expiry", null, value);
				}	
				
			}
		}

        [Browsable(false)]
       // [Category("Trade_Advanced")]
        public double PriceFirst
        {
            get
            {
                return priceFirst;
            }
            set
            {
                priceFirst = value;
            }

        }

        [Browsable(false)]
		public double BuyQuote
		{
			get 
			{ 
                return buyQuote; 
			}
			set 
			{ 
				
				buyQuote = value ; 

			}
		}
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade"), DisplayName("Price Buy")]
        public double PriceBuy
        {
            get
            {
                return buyQuote;
            }
            set
            {
                buyQuote = value;
                IPortfolio portf = this.parent as IPortfolio;
                portf.RaiseObjectChangedEvent(this, "SerializePortfolio", null, value);
             
            }
        }

        [Category("3. Performance Advanced"), DisplayName("Value - Initial")]
        public double Value_Initial
        {
            get
            {
                return FormatNumbers.FormatFloatWithTwoDigits(this.number * this.buyQuote);

            }
        }
        [Category("1. Quick Overview"), 
        DisplayName("-Value Balance")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Value_Balance
        {
            get
            {
                if (this.moneyWonLost == 0f)
                    CalculatePerformance();
                return FormatNumbers.FormatFloatWithTwoDigits(moneyWonLost);
                //return FormatNumbers.FormatFloatWithTwoDigits(this.moneyWonLost);
               
            }
        }

        [Category("3. Performance Advanced"), DisplayName("Value - Current/Sold")]
        public double Value_Current
		{
			get 
			{
                currentTotalValue = 0f;
                if (this.sold)
                {
                    currentTotalValue = this.number * this.lastPrice;
                }
                else
                {
                    currentTotalValue = CalculateValueCurrent();
                }
                return FormatNumbers.FormatFloatWithTwoDigits(currentTotalValue);
			}

		}
		//[System.Xml.Serialization.XmlIgnoreAttribute()]
		[Category("General")]
        [Browsable(false)]
		public new string ID
		{
			get
			{
				
				if(this.dataClass != null)
				{
					return this.dataClass.ID;
				}
				
				else
				{
					//the name was set on de-serialization 
                    Debug.Assert(this.iD != null, "Name of DataItem = null");
                    Debug.Assert(!String.IsNullOrEmpty(this.iD), "ID is not set");

                    return this.iD;
				}
			}
			set
			{
                this.iD = value;
                if (this.dataClass != null)
                {
                    this.dataClass.ID = value;
                }
			}
		}
		
      
	

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade"), DisplayName("Date - Buy")]
        public DateTime DateBuy
		{
			get 
			{ 
                return buyDate; 
			}
			set 
			{ 
				
				buyDate = value ;
                IPortfolio portf = this.parent as IPortfolio;
                if (portf != null)
				{
                    portf.RaiseObjectChangedEvent(this, "SerializePortfolio", null, value);
				}
			}
		}

        [Browsable(false)]
        public DateTime BuyDate
        {
            get
            {
                return buyDate;
            }
            set
            {
                buyDate = value;
            }
        }

  

        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public ITradeStep TradeStep
        {
            get
            {
                if (tradeStep == null)
                    tradeStep = new TradeStep(this);

                return tradeStep;
            }
            set
            {
                tradeStep = value;
            }
        }

        [Browsable(false)]
		public int Number
		{
			get 
			{ 
				return number; 
			}
			set 
			{ 	
				number = value ;
               
			}
		}

        [System.Xml.Serialization.XmlIgnoreAttribute()]
         [Category("1. Quick Overview"), 
        DisplayName("Number of Items")]
        public int NumberOfItems
        {
            get
            {
                return number;
            }
            set
            {
               
                number = value;
                IPortfolio portf = this.parent as IPortfolio;
                if (portf != null)
                {
                    portf.RaiseObjectChangedEvent(this, "SerializePortfolio", null, value);
                }
            }
        }

        [Category("1. Quick Overview"), 
        DisplayName("Performance %")]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public double Performance
		{
			get 
			{ 
				double f  = CalculatePerformance();
                performance = FormatNumbers.FormatDoubleWithTwoDigits(Convert.ToDouble(f));
				return performance; 
			}
		}
   
        [Category("3. Performance Advanced"), DisplayName("Performance per year (in %)")]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public double PerformancePerYear
		{
			get 
			{

                return CalculatePerformancePerYear();
			}
		}
        [Browsable(false)]
        public bool ChartCandleStick
        {
            get
            {
                return this.chartCandleStick;
            }
            set
            {
                this.chartCandleStick = value;
            }
        }
        
		[Browsable(false)]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public IDataClass DataClass
		{
			get 
			{
                DeserializeDataClass();
				return dataClass; 
			}
			set 
			{ 
				dataClass = value ;
				
                this.dataClass.Parent = this;
                dataClass.ID = this.iD;
                

			}
		}

        //  [Browsable(false)]
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public IFinancialData FinancialData
        {
            get
            {

                return this.financialData;

            }
            set
            {
                financialData = value;
            }
        }
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public FinancialData FinancialInfos
        {
            get
            {

                return this.financialData as FinancialData;

            }
            set
            {
                financialData = value;
            }
        }
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public List<IFundamentalData> FundamentalData
        {
            get
            {

                return this.fundamentalData ;

            }
            set
            {
                fundamentalData = value;
            }
        }
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public List<IFundamentalData> FundamentalData_Quartals
        {
            get
            {

                return this.fundamentalData_Quartals;

            }
            set
            {
                fundamentalData_Quartals = value;
            }
        }

        private List<FundamentalData> ConvertList(List <IFundamentalData> listOld)
        {
            List<FundamentalData> listNew = new List<FundamentalData>();
            for (int i = 0; i < listOld.Count; i++)
            {
                listNew.Add(listOld[i] as FundamentalData);
            }
            return listNew;
        }
        //  [System.Xml.Serialization.XmlIgnoreAttribute()]
        public FundamentalData[] FundamentalDataSerialize
        {
            get
            {
                if (this.fundamentalData != null)
                {
                    List<FundamentalData> fundamentalDataModified = ConvertList(this.fundamentalData);
                    if (fundamentalDataModified != null)
                    {
                        FundamentalData[] arr = (FundamentalData[])fundamentalDataModified.ToArray();
                        return arr;
                    }
                    else
                        return null;
                }
                return null;

               
            }
            set
            {
                if (value != null)
                {
                    this.fundamentalData = new List<IFundamentalData>() ;
                    for (int i = 0; i < value.Length; i++)
                    {
                        fundamentalData.Add(value[i]);
                    }
                }
            }
        }
        public FundamentalData[] FundamentalDataQuartalsSerialize
        {
            get
            {
                if (this.fundamentalData_Quartals != null)
                {
                    List<FundamentalData> fundamentalDataModified = ConvertList(fundamentalData_Quartals);
                    if (fundamentalDataModified != null)
                    {
                        FundamentalData[] arr = (FundamentalData[])fundamentalDataModified.ToArray();
                        return arr;
                    }
                    else
                        return null;
                }
                return null;


            }
            set
            {
                if (value != null)
                {
                    this.fundamentalData_Quartals = new List<IFundamentalData>();
                    for (int i = 0; i < value.Length; i++)
                    {
                        fundamentalData_Quartals.Add(value[i]);
                    }
                }
            }
        }

		[Browsable(false)]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public string[] Indicators
		{
			get
			{
				try
				{
					object[] arr = this.selectedIndicators.ToArray();
					int length = arr.Length;
					string[] retArr = new string[length];
					Array.Copy(arr,retArr,length);
					return retArr;
				}
				catch (Exception exc)
				{
					Debug.Assert(false,"DataItem - " + "Error creating ItemTypeArray ",exc.Message);
				}
				return null;
			}
			set
			{
				if(this.selectedIndicators == null)
					this.selectedIndicators = new ArrayList();

				this.selectedIndicators.Clear();
				string[] arr = value;
				for(int i = 0; i < arr.GetLength(0); i++)
				{
					this.selectedIndicators.Add(arr[i]);
				}
			}
		}

		//[System.Xml.Serialization.XmlIgnoreAttribute()]
		//this property is inserted only for serialization - because the XML serializer cannot serialize 
		// the IDataClass property !
		[Browsable(false)]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
		public DataClass Share
		{
			get 
			{ 
				return dataClass as CStock.DataClass; 
			}
			set 
			{ 
				//for deserialization
				dataClass = value;
                dataClass.Parent = this;
			}
		}
		[Browsable(false)]
		[System.Xml.Serialization.XmlIgnoreAttribute()]
        
		public DataClass ShareItem
		{
			get 
			{ 
				return dataClass as CStock.DataClass; 
			}
		}

        /// <summary>
        /// Share
        /// </summary>
        /// 
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("2. Trade")]
        [Browsable(false)]
        public string ExternalID
        {
            get
            {

                return externalID;

            }
            set
            {
                //insert the set only so that XML serialization works for this item !
                externalID = value;
            }
        }

		#endregion

		#region object overrides

		public override string ToString()
		{
			if(this.dataClass != null)
			{
				return this.dataClass.Name;
			}
			else
			{
				return base.ToString();
			}
		}

		#endregion

		#region Interface IClonable
		public override object Clone()
		{
			return this.MemberwiseClone();
		}
		#endregion

        #region properties chart

        

        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public string ProfileName
        {
            get
            {
                return profileName;

            }
            set
            {
                profileName = value;
                this.profile = null; // this will reset it ...
            }

        }
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public IProfile Profile
        {
            get
            {
                
                if (profile == null)
                {
                    if (String.IsNullOrEmpty(this.profileName))
                    {
                        profile = CStock.Profile.GetProfileDefault();
                        this.profileName = profile.ID;
                        return profile;
                       
                    }
                    else
                    {
                        profile = CStock.Profile.GetProfileByName(this.profileName);
                        if (profile == null)
                        {
                            profile = CStock.Profile.GetProfileDefault();
                            this.profileName = profile.ID;
                        }
                        Debug.Assert(profile != null, "SW Error - Chart Profile could not be found " + this.profileName);

                        return profile;
                        
                    }
                }
                else
                    return profile;

                

            }
           

        }
        [Category("Web")]
        public Web.WebStockType WebStockType
        {
            get
            {
                return this.webStockType;

            }
            set
            {

                Web.WebStockType oldval = this.webStockType;
                this.webStockType = value;
                if (oldval != this.webStockType)
                {
                    if (this.parent != null)
                    {
                        IPortfolio portf = this.parent as IPortfolio;
                        portf.RaiseObjectChangedEvent(this, "DataItem_Serialize", oldval, value);
                    }
                }	
            }
        }
        [Category("Exchange Data"), Description(@"Data related to the exchange"),
        DisplayName("Intraday Symbol ")]
        public string Symbol_Intraday 
        {
            get
            {
                return this.symbol_intraday;

            }
            set
            {

                
                this.symbol_intraday = value;
               
            }
        }
         

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public IList<string> IndicatorsOnChart
        {
            get
            {
                return indicatorsOnChart;

            }
            set
            {
                indicatorsOnChart = value;
            }

        }
        [Browsable(false)]
        public string[] IndicatorsOnChartArray
        {
            get
            {
                System.Collections.Generic.List<string> arrL = this.indicatorsOnChart as List<string>;

                if (arrL != null && arrL.Count > 0)
                    return (string[])arrL.ToArray();
                else
                    return null;
            }
            set
            {

                this.indicatorsOnChart = new List<string>();
                for (int i = 0; i < value.Length; i++)
                {
                    string s = value[i] as string;
                    indicatorsOnChart.Add(s);


                }

            }
        }

        #endregion

        #region properties trading

        /// <summary>
        /// only for TradingEconomy implementation
        /// </summary>
        /// 
        [Browsable(false)]
        [Category("Trade_Advanced")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public NameObjectCollection TradeOrders
        {
            get
            {

                return this.tradeOrders;
            }
            set
            {
                this.tradeOrders = value;
            }
        }
        [Browsable(false)]
        [Category("2. Trade")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public IOrders Orders
        {
            get
            {
                return this.orders;
            }
            set
            {
                orders = value;
            }
        }

        #endregion

        #region show web data
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double PrevClose
        {
            get
            {
                return this.financialData.PrevClose;
            }
            set
            {
                this.financialData.PrevClose = value;
            }
           
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public int Amount
        {
            get
            {
                return this.financialData.Amount;
            }
            set
            {
                this.financialData.Amount = value;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Ask
        {
            get
            {
                return this.financialData.Ask;
            }
            set
            {
                this.financialData.Ask = value;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public int AverageDailyVolume
        {
            get
            {
                return this.financialData.AverageDailyVolume;
            }
            set
            {
                this.financialData.AverageDailyVolume = value;
            }
        }
    
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Bid
        {
            get
            {
                return this.financialData.Bid;
            }
            set
            {
                this.financialData.Bid = Convert.ToDouble(value);
            }
        }
       
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double ChangeAndPercent
        {
            get
            {
                if (this.financialData != null)
                {
                    if (this.financialData.LastQuote != null)
                    {
                        if (this.financialData.LastQuote.CLOSEc != 0f)
                        {
                            return FormatNumbers.FormatFloatWithTwoDigits(this.financialData.Change / this.financialData.LastQuote.CLOSEc * 100);
                        }
                    }
                    return 0f;
                }
                return 0f;

            }
            set
            {
                
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Change
        {
            get
            {
                return this.financialData.Change;
            }
            set
            {
                this.financialData.Change = value;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double DayHigh
        {
            get
            {
                return this.financialData.DayHigh;
            }
            set
            {
                this.financialData.DayHigh = Convert.ToDouble(value);
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double DayLow
        {
            get
            {
                
                return this.financialData.DayLow;
            }
            set
            {
                this.financialData.DayLow = Convert.ToDouble(value);
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public string DayRange
        {
            get
            {
                return this.financialData.DayRange;
            }
            set
            {
                this.financialData.DayRange = value;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double DividendYield
        {
            get
            {
                return this.financialData.DividendYield;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public double LastQuote
        {
            get
            {
                if(this.financialData.LastQuote != null)
                    return this.financialData.LastQuote.CLOSEc;
                return 0f;

            }
            set
            {
                this.financialData.LastQuote.CLOSEc = value;
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public DateTime LastTradeDate
        {
            get
            {
                if (!string.IsNullOrEmpty(this.financialData.LastTradeDate))
                {
                    try
                    {

                        return Convert.ToDateTime(this.financialData.LastTradeDate, CUtil.Conversions.CultureAmerican);



                    }
                    catch// (Exception e)
                    {
                        //Debug.Assert(false, "Error converting dateTime value " + this.financialData.LastTradeDate + "; " + e.Message);
                        return DateTime.Now;
                    }
                }
                else
                {
                    return DateTime.Now;
                }
            }
            set
            {
                this.financialData.LastTradeDate = value.ToString(CUtil.Conversions.CultureAmerican);
            }
        }
        [Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        public DateTime LastTradeTime
        {
            get
            {
                try
                {
                    
                    return Convert.ToDateTime(this.financialData.LastTradeTime, CUtil.Conversions.CultureAmerican);

                }
                catch (Exception e)
                {
                    Debug.Assert(false, "Error converting dateTime value " + this.financialData.LastTradeDate + "; " + e.Message);
                    return DateTime.Now;
                }
            }
            set
            {
                this.financialData.LastTradeTime = value.ToString(CUtil.Conversions.CultureAmerican);
            }
        }
       //   <!--<Buy ColumnName="Buy" Type="double"  SampleValue="5.1"/>
       //<BuyVolume ColumnName="Buy Vol" Type="double"  SampleValue="5.1"/>-->
       //<!--<LowVolume ColumnName="Low Vol" Type="double"  SampleValue="5.1"/>-->

        #endregion

        #region implementations for properties

        private double CalculateLastPrice()
        {
            DeserializeDataClass();
            if (this.dataClass != null)
            {
                if (this.dataClass.QuoteCollection != null && this.dataClass.QuoteCollection.Count > 0)
                {
                    IQuote qu = this.dataClass.QuoteCollection[this.dataClass.QuoteCollection.Count - 1] as IQuote;
                    if (qu != null)
                        return qu.CLOSEc;

                }
            }
            return 0f;
        }
        private void CalculateInitialSellData()
        {

            this.lastPrice = CalculateLastPrice();
            if (lastPrice == 0f)
            {
                this.lastPrice = this.buyQuote;
                this.lastPrice_Date = this.buyDate;
            }
            else
            {

                string sDate = CalculateLastPriceDate();

                //this.lastPrice_Date = Convert.ToDateTime(sDate, CUtil.Conversions.CultureAmerican);
                this.lastPrice_Date = Convert.ToDateTime(sDate);


            }
        }


        private double CalculateValueCurrent()
        {
            if (this.dataClass != null)
            {

                IListQuotes qColl = dataClass.QuoteCollection;
                if (qColl != null && qColl.Count > 0)
                {
                    IQuoteBase qu = GetLastQuote(qColl);

                    if (qu != null)
                    {
                        currentTotalValue = qu.CLOSEc * this.number;
                    }
                    else
                    {
                        IQuoteBase quote = (IQuoteBase)qColl[qColl.Count];
                        if (quote != null)
                        {
                            currentTotalValue = quote.CLOSEc * this.number;
                        }
                        else
                        {
                            Debug.Assert(false, "Error calculating quote value for : " + this.DataClass.Name);
                            currentTotalValue = 0F;
                        }
                    }
                }
                else
                {
                    this.currentTotalValue = 0F;

                }
            }
            else
            {
                this.currentTotalValue = 0F;
            }
            return currentTotalValue;

        }

        private bool UpdateDataClass()
        {
            //System.Windows.Forms.MessageBox.Show("Could not get the data for the share: " + this.iD + " ... Creating default ...");

            this.dataClass.ID = this.iD;

            this.dataClass.Parent = this;
            this.dataClass.Serialize();
            return true;
        }
        private bool CreateDataClass()
        {
            //System.Windows.Forms.MessageBox.Show("Could not get the data for the share: " + this.iD + " ... Creating default ...");
            this.dataClass = new DataClassDaily();
            this.dataClass.ID = this.iD;

            this.dataClass.Parent = this;
            this.dataClass.Serialize();
            return true;
        }
        private void DeserializeDataClass()
        {
            if (dataClass == null)
            {

                object o = null;
                if (DataClassFactory.DeSerialize_DC(this.iD, ref o))
                {
                    dataClass = o as DataClassDaily;
                    dataClass.Parent = this;
                    this.financialData.Symbol = symbol;
                }
                else
                {

                    CreateDataClass();


                }


            }
        }
        public double CalculatePerformance()
        {
            if (this.number == 0)
                return 0F;
            double f = 0F;

            if (this.sold)
            {
                moneyWonLost = 0;

                if (buyQuote != 0)
                {
                    //moneyWonLost = this.lastPrice / this.buyQuote * 100;
                    moneyWonLost = (this.lastPrice - this.buyQuote) * number;
                    f = this.lastPrice * 100 / this.buyQuote - 100;
                }
                return f;

            }


            //DateTime te = this.DataClass.QuoteCollection[].DATE;

            double lastP = 0;
            IListQuotes qColl = this.DataClass.QuoteCollection;

            if (qColl == null || qColl.Count < 1)
                return -111111;
            IQuoteBase qu = GetLastQuote(qColl);




            if (qu != null)
            {
                lastP = qu.CLOSEc;
                if (this.buyQuote == 0F)
                {
                    this.buyQuote = qColl[this.buyDate].CLOSEc;
                }

                if (lastP != 0F && this.buyQuote != 0F)
                {
                    f = lastP * 100 / this.buyQuote - 100;
                    //double f = (this.value_Total - this.value_Initial) * 100 / this.value_Initial;
                }
                else
                {
                    f = 0f;
                    //Debug.Assert(false,"Could not get reference quote value ");

                }
            }
            else
            {
                Debug.Assert(false, "Could not get reference quote value ");

            }

            this.moneyWonLost = (lastP - this.buyQuote) * this.number;
            return f;

        }
        private double CalculatePerformancePerYear()
        {
            DateTime dtEnd = DateTime.Now;
            DateTime dtStart = ProgramContext.Instance.Configuration.Dates.DateMin;

            if (ProgramContext.Instance.Configuration.ProgramMode == ProgramModes.Realtime)
            {
                dtEnd = DateTime.Now;
                dtStart = this.buyDate;
            }
            else
            {
                dtEnd = ProgramContext.Instance.Configuration.Dates.DateMax;
                dtStart = ProgramContext.Instance.Configuration.Dates.DateMin;

            }


            TimeSpan diff = dtEnd - dtStart;
            int days = diff.Days;
            if (days != 0)
            {
                double perfPerYear = (this.performance * 365) / days;
                return FormatNumbers.FormatDoubleWithTwoDigits(perfPerYear);

            }
            return 0f;
        }

        #endregion

        #region implementations

        public bool AdjustBuyQuote(int numberOfItems, double price, DateTime dateBought)
        {
            double mediumPrice = (this.priceFirst * this.number + numberOfItems * price);
            mediumPrice = mediumPrice / (this.number + numberOfItems);

            this.priceFirst = mediumPrice;

            return true;

        }

        private string CalculateLastPriceDate()
        {
            if (this.dataClass != null)
            {
                if (this.dataClass.QuoteCollection != null && this.dataClass.QuoteCollection.Count > 0)
                {
                    IQuote qu = this.dataClass.QuoteCollection[this.dataClass.QuoteCollection.Count - 1] as IQuote;
                    if (qu != null)
                        return qu.DATE.ToShortDateString();
                    // return qu.DATE.ToShortDateString() + ":" + qu.DATE.Hour.ToString() + ":" + qu.DATE.Minute.ToString();

                }
            }
            return string.Empty;

        }

        #endregion

        #region for IndicatorComposed 

        public IIndicator GetOtherShareAsIndicator(string shareID)
        {
            try
            {
                IDataItem di = TradeEconomy.GetDataItemByID(shareID);
                if (di == null)
                    return null;
                IIndicator ind = new CIndicators.Indicator();
                ind.Parent = di.DataClass;

                ind.NameBase = shareID;
                ind.Interval = 0;
                ListQuotesBase doubleArr = new ListQuotesBase();//double[di.DataClass.QuoteCollection.Count];
                for (int i = 0; i < di.DataClass.QuoteCollection.Count; i++)
                {
                    IQuote qu = di.DataClass.QuoteCollection[i];

                    doubleArr.Add(new QuoteBase(qu.DATE, qu.CLOSEc));
                }
                ind.Values = doubleArr;
                return ind;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in GetOtherShareAsIndicator: " + ex.Message);
                return null;
            }

        }
        #endregion

     
    }
}
